package com.pocketsweet.ui;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLAuthentication;
import com.pocketsweet.model.MLGallery;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.fragments.SelfFragment;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_apply_for_recommend)
public class ApplyForRecommend extends BaseActivity implements OnClickListener {

	private MLUser mlUser = new MLUser();
	public static LoadingDailog loading;

	@ViewInject(R.id.mainHeader)
	private static HeaderLayout header;

	@ViewInject(R.id.edtContact)
	private static EditText edtContact;

	@ViewInject(R.id.edtArticle)
	private static EditText edtArticle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mlUser = UserService.getCurrentUser();
		initView();
		setHeaderFunction();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (IdentificationPhoto.photo != null) {
			IdentificationPhoto.photo = null;
		}
		if (IdentificationPhoto.cropPath != null) {
			IdentificationPhoto.cropPath = null;
		}
		if (!StringUtils.isEmpty(IdentificationPhoto.photoPath)) {
			IdentificationPhoto.photoPath = null;
		}
	}

	private void initView() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		edtContact = (EditText) findViewById(R.id.edtContact);
		edtArticle = (EditText) findViewById(R.id.edtArticle);
		AVQuery<MLAuthentication> query = new AVQuery<MLAuthentication>(
				"MLAuthentication");
		query.whereEqualTo("sponsor", mlUser);
		query.findInBackground(new FindCallback<MLAuthentication>() {
			public void done(List<MLAuthentication> mlAuthenticationList,
					AVException e) {
				if (e == null) {
					if (mlAuthenticationList.size() > 0) {// 已经提交过认证
						MLAuthentication mlAuthentication;
						int i;
						for (i = 0; i < mlAuthenticationList.size(); i++) {
							mlAuthentication = mlAuthenticationList.get(i);
							if (mlAuthentication.getStatus() == C.IDENTIFICATION_STATUS_WAITING) {
								ToolKits.toast(ApplyForRecommend.this,
										"您已有申请资料在审核中");
								break;
							}
						}
					}
				} else {
					ToolKits.toast(ApplyForRecommend.this, "网络似乎断开了");
				}
			}
		});
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("提交");
		header.setMiddleText("申请");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				if (StringUtils.isEmpty(edtArticle.getText().toString())
						&& StringUtils.isEmpty(edtContact.getText().toString())) {
					ApplyForRecommend.this.finish();
					return;
				}
				final MyAlertDialog dialog = new MyAlertDialog(
						ApplyForRecommend.this).builder()
						.setMsg("如果放弃，此次的编辑内容将不会保存，确定放弃？").setTitle("提示")
						.setNegativeButton("取消", new OnClickListener() {
							@Override
							public void onClick(View v) {

							}
						});
				dialog.setPositiveButton("确定", new OnClickListener() {
					@SuppressLint("SimpleDateFormat")
					@Override
					public void onClick(View v) {
						ApplyForRecommend.this.finish();
					}
				});
				dialog.show();
			}
		});
		header.setRighttContainerClickListener(new onRightContainerListener() {

			@Override
			public void onClick() {
				if (StringUtils.isEmpty(edtContact.getText().toString())
						|| StringUtils.isEmpty(edtArticle.getText().toString())
						|| edtArticle.getText().length() < 50) {
					ToolKits.toast(ApplyForRecommend.this, "请完善信息");
					return;
				}
				loading = ToolKits.createLoadingDialog(ApplyForRecommend.this,
						"提交中..");
				loading.setText("加载中");
				loading.show();
				AVQuery<MLAuthentication> query = new AVQuery<MLAuthentication>(
						"MLAuthentication");
				query.whereEqualTo("sponsor", mlUser);
				query.findInBackground(new FindCallback<MLAuthentication>() {
					public void done(
							List<MLAuthentication> mlAuthenticationList,
							AVException e) {
						if (e == null) {
							if (mlAuthenticationList.size() > 0) {// 已经提交过认证
								MLAuthentication mlAuthentication;
								int i;
								for (i = 0; i < mlAuthenticationList.size(); i++) {
									mlAuthentication = mlAuthenticationList
											.get(i);
									if (mlAuthentication.getStatus() == C.IDENTIFICATION_STATUS_WAITING) {
										loading.dismiss();
										ToolKits.toast(ApplyForRecommend.this,
												"您已有申请资料在审核中");
										break;
									}
								}
								if (i >= mlAuthenticationList.size()) { // 可以申请
									submit();
								}
							} else {
								submit();
							}
						} else {
							ToolKits.toast(ApplyForRecommend.this, "网络似乎断开了");
						}
					}
				});

			}
		});
	}

	private void submit() {
		MLAuthentication mlAuthentication = new MLAuthentication();
		mlAuthentication.setContact(edtContact.getText().toString());
		mlAuthentication.setStory(edtArticle.getText().toString());
		mlAuthentication.setNeedRecommend(C.IDENTIFICATION_STATUS_TOBE);
		mlAuthentication.saveInBackground(new SaveCallback() {

			@Override
			public void done(AVException e) {
				loading.dismiss();
				if (e == null) {
					AVAnalytics.onEvent(ApplyForRecommend.this, "申请成为梦想恋人");
					final MyAlertDialog dialog = new MyAlertDialog(
							ApplyForRecommend.this).builder()
							.setMsg("你已成功提交认证资料，正在审核中").setTitle("提示")
							.setPositiveButton("确定", new OnClickListener() {
								@Override
								public void onClick(View v) {
									ApplyForRecommend.this.finish();
								}
							});
					dialog.show();
				} else {
					ToolKits.toast(ApplyForRecommend.this, "网络似乎断开了");
				}
			}
		});
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.relPhoto:
			Intent intentPhoto = new Intent(ApplyForRecommend.this,
					IdentificationPhoto.class);
			startActivity(intentPhoto);
			break;
		case R.id.relProfile:
			Intent intent = new Intent(ApplyForRecommend.this,
					ProfileEdit.class);
			startActivity(intent);
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 此处写处理的事件
			ApplyForRecommend.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

}
